package com.group.app.example.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;

import com.group.app.example.handle.CustomRowWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
public class DownloadUtil {

    public static  void excelDownload(HttpServletResponse response, List<?> data, Class className){
        WriteCellStyle headWriteCellStyle =new WriteCellStyle();
        headWriteCellStyle.setFillPatternType(FillPatternType.DIAMONDS);
        headWriteCellStyle.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        WriteCellStyle contentWriteCellStyle =new WriteCellStyle();
        HorizontalCellStyleStrategy horizontalCellStyleStrategy=new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle);
        response.setCharacterEncoding("utf-8");
        response.addHeader("Access-Control-Expose-Headers","content-disposition");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系

        try {
            EasyExcel.write(response.getOutputStream(),className)
                     .registerWriteHandler(CellStyleUtil.getHorizontalCellStyleStrategy())
                    .registerWriteHandler(new CustomRowWriteHandler())
                    .sheet("sheet1")
                    .doWrite(data);
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
